﻿using System;
using System.Linq;
using System.Linq.Expressions;
using Fuse8.DomainFramework.Common;

namespace Fuse8.DomainFramework.DataAccess.ExpressionSlicers
{
    /// <summary>
    /// 
    /// </summary>
    public class SlicerHelper
    {
        /// <summary>
        /// 
        /// </summary>
        /// <param name="expression"></param>
        /// <typeparam name="TEntity"></typeparam>
        /// <returns></returns>
        public static Expression<Func<TEntity, bool>> AdaptEpression<TEntity>(Expression<Func<TEntity, bool>> expression)
        {
            var slicer = SlicerServiceFacade.Scope.GetCurrentSlicer(typeof (TEntity));
            if (slicer != null)
            {
                if (expression != null)
                {
                    var lambdaExpression = slicer.And(expression);
                    expression = Expression.Lambda<Func<TEntity, bool>>(lambdaExpression.Body, lambdaExpression.Parameters.ToArray());
                }
                else
                {                    
                    expression = Expression.Lambda<Func<TEntity, bool>>(slicer.Body, slicer.Parameters.ToArray());
                }
            }
            return expression;
        }
    }
}